<?php
/**
 * ProjectName: Grapes.
 * Created by LemonZ.
 * FileName: GoodsTypeSpecRel.php
 * Date: 2019/2/14
 * Time: 1:25
 * Description: 商品属性
 */

namespace app\common\model;


class GoodsTypeSpecRel extends Common
{
    /**
     * @return \think\model\relation\HasOne
     */
    public function getSpec()
    {
        return $this->hasOne('GoodsTypeSpec','id','spec_id');
    }

    /**
     * 更新类型和参数
     * @param int $type_id
     * @param array $specs_id
     * @return bool|\think\Collection
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updateTypeSpec($type_id=0,$specs_id=[])
    {
        if(!$type_id||!$specs_id)
        {
            return false;
        }
        $typeSpecRelModel = $this->where(['type_id' => $type_id])->field('type_id');
        if($typeSpecRelModel->select()){
            $typeSpecRelModel->delete();
        }
        $iData = [];
        foreach($specs_id as $key=>$val)
        {
            $iData[] = [
                'type_id'=>$type_id,
                'spec_id'=>$val
            ];
        }
        return $this->saveAll($iData);
    }

    /**
     * 获取类型关联参数
     * @param int $type_id
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRelTypeSpec($type_id=0)
    {
        if(!$type_id){
            return false;
        }
        $data = [];
        $goodsTypeSpecModel = new GoodsTypeSpec();
        $typeSpecs = $this->where(['type_id' => $type_id])->select();

        if(!$typeSpecs->isEmpty()){
            foreach ((array)$typeSpecs->toArray() as $k=>$v)
            {
                $data[$k]['type_id'] = $v['type_id'];
                $data[$k]['spec_id'] = $v['spec_id'];
                $data[$k]['spec'] = $goodsTypeSpecModel->getSpecInfo($v['spec_id']);
            }
        }
        return $data;
    }
}